//
//  GYOrderEvaluateViewController.m
//  GoodLuck
//
//  Created by apple on 2018/3/23.
//  Copyright © 2018年 yunjiazhineng. All rights reserved.
//

#import "GYOrderEvaluateViewController.h"
#import "GYOrderEvaluateTableViewCell.h"
#import "GYOrderEvaluateFootView.h"
#import "GYNetWorkTools.h"



@interface GYOrderEvaluateViewController ()<UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;

/** 该订单的相册ID */
@property (nonatomic, strong) NSString *ac_id;

/** 记录当前选择图片的按钮 */
@property (nonatomic, strong) UIButton *currentSelectBtu;

/** 记录当前上传的图片名字 */
@property (nonatomic, strong) NSMutableArray *imageFileNames;

//代表是否匿名评价
@property (nonatomic, getter=isAnonymous) BOOL anonymous;

/** 缓存每个商品的评价分数 */
@property (nonatomic, strong) NSMutableDictionary *cachesGoodsScore;

/** 缓存是否匿名 */
@property (nonatomic, strong) NSMutableDictionary *cachesGoodsAnonymous;

/** 缓存每个商品的评价意见 */
@property (nonatomic, strong) NSMutableDictionary *cachesGoodsEvaluate;

/** 缓存每个商品的图片评价 */
@property (nonatomic, strong) NSMutableDictionary *cachesGoodsEvaluateImage;

/** 当前选择商品的图片 */
@property (nonatomic, strong) NSString *currentGoods_id;
@end

@implementation GYOrderEvaluateViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    

    //初始化
    [self setupUI];
}

- (void)setupUI {
    self.navigationItem.title = @"订单评价";
    
    //设置表格的属性
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, CGFLOAT_MIN)];
    self.tableView.sectionHeaderHeight = 0;
    self.tableView.rowHeight = 190;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    //加载评价订单详情信息
    [self loadOrderEvaluateDetailsInfo];
}

- (void)loadOrderEvaluateDetailsInfo {
    [EasyLodingView showLodingText:@"正在加载..." config:^EasyLodingConfig *{
        EasyLodingConfig *config = [EasyLodingConfig shared];
        config.showOnWindow = YES;
        
        return config;
    }];
    [GYNetWorkTools requestOrderEvaluateDetailsInfo:[[self.orderGoodsList firstObject] order_id] success:^(NSDictionary *obj) {
        int code = [[obj objectForKey:@"code"] intValue];
        NSDictionary *datas = [obj objectForKey:@"datas"];
        if (code == 200) {
            [EasyLodingView hidenLoingInView:[UIApplication sharedApplication].keyWindow];
            self.ac_id = [datas objectForKey:@"ac_id"];
        }else if (code == 400) {
            [EasyLodingView hidenLoingInView:[UIApplication sharedApplication].keyWindow];
            [EasyTextView showText:@"加载数据出错,请重新加载!"];
            NSLog(@"error= =====%@",[datas objectForKey:@"error"]);
        }
    } error:^(NSError *error) {
        [EasyLodingView hidenLoingInView:[UIApplication sharedApplication].keyWindow];
        [EasyTextView showText:@"加载数据出错,请重新加载!"];
        NSLog(@"OrderEvaluateDetailsInfoFailed===%@",error);
    }];
}

#pragma mark -- UITableViewDelegate,UITableViewDataSource 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.orderGoodsList.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    GYOrderEvaluateTableViewCell *cell = [GYOrderEvaluateTableViewCell cellWithtTableview:tableView];
    cell.goodsEvaluate = self.orderGoodsList[indexPath.section];
    __weak typeof(self) weakSelf = self;
    cell.updateSelectBtuCallBack = ^(UIButton *sender, BOOL isAnonymous, NSString *goods_id) {
        if (isAnonymous) {
            [weakSelf.cachesGoodsAnonymous setObject:@"1" forKey:[weakSelf.orderGoodsList[indexPath.section] goods_id]];
        }else {
            [weakSelf.cachesGoodsAnonymous setObject:@"" forKey:[weakSelf.orderGoodsList[indexPath.section] goods_id]];
        }
        weakSelf.currentSelectBtu = sender;
        weakSelf.anonymous = isAnonymous;
        weakSelf.currentGoods_id = goods_id;
        
        NSArray *mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeSavedPhotosAlbum];
        UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
        ipc.delegate = weakSelf;
        //1.获取系统相机支持的媒体格式 (这个参数不管填写什么都返回所有的支持格式)
        //设置你要支持的媒体格式
        ipc.mediaTypes = mediaTypes;
        
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        
        
        UIAlertAction *cameraBtu = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
                [self presentViewController:ipc animated:YES completion:nil];
            }
        }];
        
        UIAlertAction *libraryBtu = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
                //3.设置 图片或是视频的来源和支持的媒体格式
                //设置你数据的来源
                ipc.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
                [weakSelf presentViewController:ipc animated:YES completion:nil];
            }
        }];
        
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"点击取消按钮/...");
        }];
        
        [alertController addAction:cameraBtu];
        [alertController addAction:libraryBtu];
        [alertController addAction:cancel];
        
        [weakSelf presentViewController:alertController animated:YES completion:nil];

    };
    //缓存商品评分
    cell.cachesGoodsScoreCallBack = ^(NSInteger score) {
        [weakSelf.cachesGoodsScore setObject:@(score) forKey:[weakSelf.orderGoodsList[indexPath.section] goods_id]];
    };
    
    //缓存商品文字评价
    cell.cachesGoodsEvalauteCallBack = ^(NSString *evaluate) {
        [weakSelf.cachesGoodsEvaluate setObject:evaluate forKey:[weakSelf.orderGoodsList[indexPath.section] goods_id]];
    };
    
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (section == self.orderGoodsList.count-1) {
        GYOrderEvaluateFootView *footView = [[[NSBundle mainBundle] loadNibNamed:@"GYOrderEvaluateFootView" owner:nil options:nil] firstObject];
        footView.frame = CGRectMake(0, 0, ScreenWidth, 210);
        __weak typeof(self) weakSelf = self;
        
        footView.subOrderEvaluateCallBack = ^(NSInteger des, NSInteger ser, NSInteger dev) {
            //设置参数
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            for (int i = 0 ; i< weakSelf.orderGoodsList.count; i++) {
                GYOrderGoods *model = weakSelf.orderGoodsList[section];
                NSString *key = [NSString stringWithFormat:@"goods[%@][score]",model.rec_id];
                NSString *key1 = [NSString stringWithFormat:@"goods[%@][anony]",model.rec_id];
                NSString *key2 = [NSString stringWithFormat:@"goods[%@][comment]",model.rec_id];
                NSString *key3 = [NSString stringWithFormat:@"goods[%@][evaluate_image]",model.rec_id];
                
                NSInteger score = [[weakSelf.cachesGoodsScore objectForKey:model.goods_id] floatValue];
                if (score == 0) {
                    [EasyTextView showText:@"请选择商品评分!"];
                    return ;
                }
                [dic setValue:[NSString stringWithFormat:@"%zd",score] forKey:key];
                
                NSString *anonymous = [weakSelf.cachesGoodsAnonymous objectForKey:model.goods_id];
                [dic setObject:anonymous == nil ? @"" :anonymous forKey:key1];
                
                NSString *comment = [weakSelf.cachesGoodsEvaluate objectForKey:model.goods_id];
                if (comment.length == 0) {
                    [EasyTextView showText:@"请输入商品评价!"];
                    return;
                }
                [dic setObject:comment == nil ? @"" : comment forKey:key2];
                
                //图片
                NSArray *images = [weakSelf.cachesGoodsEvaluateImage objectForKey:model.goods_id];
                [dic setObject:images == nil ? @[] : images forKey:key3];
            }
            
            if (des == 0 || ser == 0 || dev == 0) {
                [EasyTextView showText:@"请选择店铺评价!"];
                return;
            }
            
            //提交订单评价
            [GYNetWorkTools requestSubmitOrderEvaluate:dic order_id:[[weakSelf.orderGoodsList firstObject] order_id] store_desccredit:[NSString stringWithFormat:@"%zd",des] store_servicecredit:[NSString stringWithFormat:@"%zd",ser] store_deliverycredit:[NSString stringWithFormat:@"%zd",dev] success:^(NSDictionary *obj) {
                
                //NSLog(@"obj ======%@",obj);
                int code = [[obj objectForKey:@"code"] intValue];
                if (code == 200) {
                    [EasyTextView showSuccessText:@"提交评价成功!"];
                    [self.navigationController popViewControllerAnimated:YES];
                }else if (code == 400) {
                    [EasyTextView showText:@"提交评价失败!"];
                }
            } error:^(NSError *error) {
                [EasyTextView showText:@"提交评价失败!"];
                NSLog(@"SubmitOrderEvaluateFailed====%@",error);
            }];
        };
        
        return footView;
    }else {
        UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 10)];
        bgView.backgroundColor = [UIColor clearColor];
        
        return bgView;
    }
}

- (CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == self.orderGoodsList.count-1) {
        return 210;
    }
    
    return 10;
}

#pragma mark -- UIImagePickerControllerDelegate,UINavigationControllerDelegate

//适用获取所有媒体资源，只需判断资源类型
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    //把图片数据缓存起来  然后等待上传
    NSData *data = UIImageJPEGRepresentation(image, 0.5);
    
    //执行图片上传操作
    [EasyLodingView showLodingText:@"正在上传图片" config:^EasyLodingConfig *{
        EasyLodingConfig *config = [EasyLodingConfig shared];
        config.showOnWindow = YES;
        config.superReceiveEvent = NO;
        
        return config;
    }];
    [GYNetWorkTools requestOrderEvaluateUploadImage:self.ac_id imageData:data success:^(NSDictionary *obj) {
        //NSLog(@"obj==============%@",obj);
        int code = [[obj objectForKey:@"code"] intValue];
        NSDictionary *datas = [obj objectForKey:@"datas"];
        if (code == 200) {
            [EasyLodingView hidenLoingInView:[UIApplication sharedApplication].keyWindow];
            //这里应该要给按钮设置图片和状态
            [self.currentSelectBtu setBackgroundImage:image forState:UIControlStateNormal];
            
            NSString *file_name = [datas objectForKey:@"file_name"];
            NSMutableArray *images = [self.cachesGoodsEvaluateImage objectForKey:self.currentGoods_id];
            if (images == nil) {
                images = [NSMutableArray array];
                [images addObject:file_name];
            }else {
                if (self.currentSelectBtu.selected) {
                    [images replaceObjectAtIndex:self.currentSelectBtu.tag-1 withObject:file_name];
                }else {
                    [images addObject:file_name];
                }
            }
            self.currentSelectBtu.selected = YES;
            //设置图片
            [self.cachesGoodsEvaluateImage setObject:images forKey:self.currentGoods_id];
        }else if (code == 400) {
            [EasyLodingView hidenLoingInView:[UIApplication sharedApplication].keyWindow];
            [EasyTextView showText:@"上传图片失败,请重新上传!"];
            NSLog(@"error==========%@",[datas objectForKey:@"error"]);
        }
    } error:^(NSError *error) {
        [EasyLodingView hidenLoingInView:[UIApplication sharedApplication].keyWindow];
        [EasyTextView showText:@"上传图片失败,请重新上传!"];
        NSLog(@"OrderEvaluateUploadImageFaile===%@",error);
    }];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 懒加载

- (NSMutableArray *)imageFileNames {
    if (!_imageFileNames) {
        _imageFileNames = [NSMutableArray array];
    }
    
    return _imageFileNames;
}

- (NSMutableDictionary *)cachesGoodsScore {
    if (!_cachesGoodsScore) {
        _cachesGoodsScore = [NSMutableDictionary dictionary];
    }
    
    return _cachesGoodsScore;
}

- (NSMutableDictionary *)cachesGoodsAnonymous {
    if (!_cachesGoodsAnonymous) {
        _cachesGoodsAnonymous = [NSMutableDictionary dictionary];
    }
    
    return _cachesGoodsAnonymous;
}

- (NSMutableDictionary *)cachesGoodsEvaluate {
    if (!_cachesGoodsEvaluate) {
        _cachesGoodsEvaluate = [NSMutableDictionary dictionary];
    }
    
    return _cachesGoodsEvaluate;
}

- (NSMutableDictionary *)cachesGoodsEvaluateImage {
    if (!_cachesGoodsEvaluateImage) {
        _cachesGoodsEvaluateImage = [NSMutableDictionary dictionary];
    }
    
    return _cachesGoodsEvaluateImage;
}
@end
